﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace WindowsFormsOpenXML
{
    public partial class Form1 : Form
    {
        private List<SubForm> subForms = new List<SubForm>();
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (subForms.Count < 3)
            {
                SubForm newSubForm = new SubForm();
                newSubForm.Text = "SubForm " + (subForms.Count + 1);
                newSubForm.Show();
                subForms.Add(newSubForm);
            }
            else
            {
                subForms[subForms.Count - 1].Activate();
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SerializeWindowState();
        }

        private void SerializeWindowState()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<FormWindowState>));
            using (FileStream fs = new FileStream("window_state.xml", FileMode.Create))
            {
                List<FormWindowState> windowStates = new List<FormWindowState>();
                foreach (var form in subForms)
                {
                    windowStates.Add(form.WindowState);
                }
                serializer.Serialize(fs, windowStates);
            }
        }

        private void DeserializeWindowState()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<FormWindowState>));
            if (File.Exists("window_state.xml"))
            {
                using (FileStream fs = new FileStream("window_state.xml", FileMode.Open))
                {
                    List<FormWindowState> windowStates = (List<FormWindowState>)serializer.Deserialize(fs);
                    for (int i = 0; i < Math.Min(windowStates.Count, subForms.Count); i++)
                    {
                        subForms[i].WindowState = windowStates[i];
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DeserializeWindowState();
        }
    }
}
